<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\analysis\material;

use app\command\BaseWork;
use app\model\mongo\MongoStatModel;
use app\service\analysis\data\material\MaterialMonthStatService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class MaterialMonthStatWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('analysis_material_month_stat_work');
        // 设置参数
        $this->setDescription('数据分析-素材月汇总')
            ->addArgument('task_type', Argument::REQUIRED, '任务类型  2：视频  3：图片')
            ->setHelp('php think analysis_material_month_stat_work [task_type]');
    }

    /**
     * @param Input $input
     * @param Output $output
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $taskType = intval($input->getArgument('task_type'));

        // 超过5min就停止
        $t = time();
        $runTime = 5 * 60;
        while (time() - $t <= $runTime) {
            $obj = new MaterialMonthStatService($taskType);
            $items = $obj->getList();
            if (count($items) == 0) {
                $this->getOutputMessage('暂无数据睡眠中');
                sleep(rand(5, 10));
                continue;
            }
            foreach ($items as $model) {
                try {
                    if (! $model instanceof MongoStatModel || ! $model->getKey()) {
                        $this->getOutputMessage('素材日汇总对象错误');
                    }

                    $this->getOutputMessage('同步[' . $model->getKey() . ']开始');
                    if (! $obj->runTask($model)) {
                        $this->getOutputMessage('同步[' . $model->getKey() . ']失败:' . $obj::getError(0));
                    }
                    $this->getOutputMessage('同步[' . $model->getKey() . ']完成');
                } catch (\Exception $e) {
                    $this->getOutputMessage('错误：' . $e->getMessage());
                    echo $e->getLine() . PHP_EOL;
                    echo $e->getFile() . PHP_EOL;
                    echo $e->getTraceAsString() . PHP_EOL;
                }
            }
        }
        $this->getOutputMessage('素材追加结束');
    }
}
